<?php
/**
 * Created by PhpStorm.
 * User: kaodou
 * Date: 2017/12/28
 * Time: 14:11
 */
namespace App\Api\Service\Search\Controllers;

use App\Eloquent\Ygt\Privilege;
use App\Eloquent\Ygt\ProductFields;
use Framework\BaseClass\Api\Controller;
use App\Eloquent\Ygt\OrderListRelation;
use App\Eloquent\Ygt\Product;
use App\Eloquent\Ygt\DepartmentUser;
use App\Engine\Product as EngineProduct;
use App\Engine\Func;
use App\Engine\OrderEngine;

class IndexController extends Controller
{
    public function index(){

        $queryType = request('query_type','all');

        if($queryType == 'all'){
            $limit = 6;
            $offset = 0;
        }else{
            $page = request('page',1);
            $limit = 10;
            $offset = ($page - 1)*$limit;
        }

        $result = [];
        $userId = Func::getHeaderValueByName('userid');
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';
        $privilegeId = isset($userInfo['privilege_id']) ? $userInfo['privilege_id'] : 0;
        $keyword = request('keyword');


        //如果没有查看库存的权限，不显示库存信息
        $privilegeAppnode  = Privilege::getAppnodeList( $privilegeId )->toArray();
        $isAbleProduct = false;
        foreach ($privilegeAppnode as $privilegeAppnodeRow){
            if($privilegeAppnodeRow['id'] == 3){
                $isAbleProduct = true;
            }
        }

        $productList = [];
        if(($queryType == 'product' or $queryType == 'all') && $isAbleProduct){

            $where              = ['product_name'=>['like','%'.$keyword.'%']];
            //取列表
            $productList        = Product::getListByJoin($where,$limit,$offset)->toArray();
            //取材料的自定义属性值
            $productIdArr       = [];
            foreach($productList as $key=>$val)
            {
                $productIdArr[] = $val['id'];
            }
            $where              = ['product_id'=>['in',$productIdArr]];
            $customFieldsArr    = ProductFields::getTransformListToArr($where);
            //转换列表
            $otherArr           = ['custom_fields_arr'=>$customFieldsArr];
            $productList        = Product::transformListByType($productList,$otherArr);

            if($queryType == 'product') {
                //取总数
                $where          = ['product_name'=>['like','%'.$keyword.'%']];
                $count          = Product::getCount($where);
            }
        }
        if($queryType == 'order' or $queryType == 'all') {

            $field = [
                "*"
            ];

            $orderListRelationModel = new OrderListRelation();

            $orderList = $orderListRelationModel
                ->select($field)
                ->skip($offset)
                ->take($limit)
                ->orderBy('ygt_order_list_relation.id','desc')
                ->where([
                    ['uid','=', $userId ],
                    ['company_id','=', $companyId ],
                    ['content','like', '%' . $keyword . '%']
                ])
                ->get();
            $orderList = $orderList->map(function($item){
                $orderInfo = unserialize($item->content);

                $re = OrderEngine::getOrderListRelationStatusStr($item->type,$item->status);

                //工单数量
                $tmpArr = explode(',', $orderInfo['product_num']);
                $productNum = $tmpArr[0];
                if (!$productNum || !is_numeric($productNum)) {
                    $productNum = '';
                }else{
                    if(count($tmpArr) == 2){
                        $productNum = $tmpArr[0].$tmpArr[1];
                    }
                }

                //客户名称
                $customerName = \App\Engine\Customer::getNameById($orderInfo['customer_name']);
                if (!$customerName) {
                    $customerName = $orderInfo['customer_name'];
                }

                //接单人
                $orderMeet = '暂无';
                $tmpProcessWhere = [];
                $tmpProcessWhere[] = ['order_id','=',$orderInfo['id']];
                $tmpProcessWhere[] = ['uid','!=',$item->uid];
                $tmpProcessWhere[] = ['uid','!=',''];
                $orderProcessObj = \App\Eloquent\Ygt\OrderProcess::where($tmpProcessWhere)->first();
                if($orderProcessObj){
                    if(DepartmentUser::getCurrentInfo($orderProcessObj->uid)){
                        $userInfo = DepartmentUser::getCurrentInfo($orderProcessObj->uid)->toArray();
                        $orderMeet = $userInfo['truename'].'等';
                    }
                }


                $tmp = [
                    'order_time' => date('Y-m-d H:i:s',$item->order_create_time),
                    'order_status' => $re['title'],
                    'function_name' => $re['function_name'],
                    'type' => $item->type,
                    'id' => $item->relate_id,
                    'order_title' => $item->order_title,
                    'order_meet' => $orderMeet,
                    'order_number' => $productNum,
                    'customer_name' => $customerName,
                ];
                return $tmp;
            });

/*
            $orderList = [
                [
                    'order_time' => date('Y-m-d H:i:s'),
                    'order_status' => '待接单',
                    'order_title' => 'D201711320087',
                    'order_meet' => '接单人',
                    'order_number' => '1000条',
                ]
            ];
*/
            $result['order'] = $orderList;

            if($queryType == 'order') {
                $count = 1;
            }

        }



        if($queryType == 'user' or $queryType == 'all') {
            $departmentUserModel = new DepartmentUser();
            $departCollection   = Privilege::getDepartmentList($privilegeId);
            $departIdArr        = $departCollection->keyBy('id')->keys()->toArray();
            $userList = $departmentUserModel
                ->select([
                    'ygt_department_user.truename',
                    'ygt_department_user.mobile',
                    'ygt_department_user.user_id',
                    'ygt_department.title as department_title',
                    'ygt_user.avatar',
                    'ygt_department_user.id',
                ])
                ->skip($offset)
                ->take($limit)
                ->orderBy('ygt_department_user.id', 'desc')
                ->where([
                    ['ygt_department_user.company_id', '=', $companyId]
                ])
                ->whereIn('department_id',$departIdArr)
                ->where(
                    function ($query) use ($keyword) {
                        $query->where([
                            ['ygt_department_user.truename', 'like', '%' . $keyword . '%']
                        ])
                            ->orWhere([
                                ['ygt_department_user.mobile', 'like', '%' . $keyword . '%']
                            ]);
                    }
                )
//            ->leftJoin('ygt_img_upload','ygt_product.img_id','=','ygt_img_upload.id')
                ->leftJoin('ygt_department', 'ygt_department_user.department_id', '=', 'ygt_department.id')
                ->leftJoin('ygt_user', 'ygt_department_user.user_id', '=', 'ygt_user.id')
                ->get();

            $userList->transform(function ($item) {
                $item->avatar = Func::getImgUrlById($item->avatar);
                return $item;
            });
            $result['user'] = $userList;

            if($queryType == 'user'){

                $count = $departmentUserModel
                    ->where([
                        ['ygt_department_user.company_id', '=', $companyId]
                    ])
                    ->where(
                        function ($query) use ($keyword) {
                            $query->where([
                                ['ygt_department_user.truename', 'like', '%' . $keyword . '%']
                            ])
                                ->orWhere([
                                    ['ygt_department_user.mobile', 'like', '%' . $keyword . '%']
                                ]);
                        }
                    )
                    ->count();
            }

        }


        if($queryType == 'all') {
            return ['product'=>$productList,'order'=>$orderList,'user'=>$userList];
        }
        $pagingData = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($result, $pagingData);

    }
}



















